<template>
  <div class="share-container">
    <el-container>
      <!-- 顶部导航 -->
      <el-header class="header">
        <div class="header-left">
          <h2>YY云盘</h2>
        </div>
        <div class="header-right">
          <el-dropdown @command="handleCommand">
            <span class="user-info">
              <el-icon><User /></el-icon>
              {{ userStore.userInfo?.nickname || '用户' }}
              <el-icon><ArrowDown /></el-icon>
            </span>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="profile">个人信息</el-dropdown-item>
                <el-dropdown-item command="logout" divided>退出登录</el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </div>
      </el-header>

      <el-container>
        <!-- 侧边栏 -->
        <el-aside width="150px" class="sidebar">
          <el-menu
            :default-active="$route.path"
            router
            background-color="#f5f5f5"
            text-color="#333"
            active-text-color="#409eff"
          >
            <el-menu-item index="/files">
              <el-icon><Folder /></el-icon>
              <span>我的文件</span>
            </el-menu-item>
            <el-menu-item index="/uploads">
              <el-icon><Upload /></el-icon>
              <span>上传列表</span>
            </el-menu-item>
            <el-menu-item index="/share">
              <el-icon><Share /></el-icon>
              <span>我的分享</span>
            </el-menu-item>
            <el-menu-item index="/recycle">
              <el-icon><Delete /></el-icon>
              <span>回收站</span>
            </el-menu-item>
          </el-menu>
        </el-aside>

        <!-- 主内容区 -->
        <el-main class="main-content">

          <!-- 工具栏 -->
          <div class="toolbar">
        <div class="toolbar-left">
          <el-button-group>
            <el-button :type="shareType === 'all' ? 'primary' : ''" @click="shareType = 'all'">
              全部分享
            </el-button>
            <el-button :type="shareType === 'active' ? 'primary' : ''" @click="shareType = 'active'">
              有效分享
            </el-button>
            <el-button :type="shareType === 'expired' ? 'primary' : ''" @click="shareType = 'expired'">
              已过期
            </el-button>
          </el-button-group>
        </div>
        <div class="toolbar-right">
          <el-button type="primary" @click="$router.push('/files')">
            <el-icon><Share /></el-icon>
            去创建分享
          </el-button>
          <el-input
            v-model="searchKeyword"
            placeholder="搜索分享文件"
            style="width: 200px; margin-left: 10px"
            clearable
            @clear="handleSearch"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><Search /></el-icon>
            </template>
          </el-input>
        </div>
      </div>

          <!-- 分享列表 -->
        <div v-loading="loading" class="share-content">
          <el-table
            :data="shareList"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" />
            <el-table-column label="分享文件" min-width="300">
              <template #default="scope">
                <div class="file-name-cell">
                  <el-icon class="file-icon" :size="20">
                    <Folder v-if="scope.row.isFolder" />
                    <Document v-else />
                  </el-icon>
                  <span class="file-name">{{ scope.row.fileName }}</span>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="分享链接" width="300">
              <template #default="scope">
                <div class="share-link">
                  <span class="link-text">{{ scope.row.shareUrl }}</span>
                  <el-button size="small" text @click="copyShareLink(scope.row)">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                </div>
              </template>
            </el-table-column>
            <el-table-column label="提取码" width="100">
              <template #default="scope">
                <span v-if="scope.row.password">{{ scope.row.password }}</span>
                <span v-else class="no-password">无</span>
              </template>
            </el-table-column>
            <el-table-column label="访问次数" width="100">
              <template #default="scope">
                {{ scope.row.visitCount }}
              </template>
            </el-table-column>
            <el-table-column label="有效期" width="120">
              <template #default="scope">
                <el-tag v-if="scope.row.status === 1" type="success">有效</el-tag>
                <el-tag v-else type="danger">已过期</el-tag>
              </template>
            </el-table-column>
            <el-table-column label="创建时间" width="180">
              <template #default="scope">
                {{ formatTime(scope.row.createTime) }}
              </template>
            </el-table-column>
            <el-table-column label="过期时间" width="180">
              <template #default="scope">
                <span v-if="scope.row.expireTime">{{ formatTime(scope.row.expireTime) }}</span>
                <span v-else>永久有效</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="250">
              <template #default="scope">
                <el-button-group>
                  <el-button size="small" @click="handleViewShare(scope.row)" title="查看详情">
                    <el-icon><View /></el-icon>
                  </el-button>
                  <el-button size="small" @click="handleEditShare(scope.row)" title="编辑分享">
                    <el-icon><Edit /></el-icon>
                  </el-button>
                  <el-button size="small" @click="copyShareLink(scope.row)" title="复制链接">
                    <el-icon><CopyDocument /></el-icon>
                  </el-button>
                  <el-button size="small" type="danger" @click="handleCancelShare(scope.row)" title="取消分享">
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </el-button-group>
              </template>
            </el-table-column>
          </el-table>

          <!-- 空状态 -->
          <el-empty v-if="!loading && shareList.length === 0" description="暂无分享记录" />
        </div>

        <!-- 分页 -->
        <div class="pagination" v-if="total > 0">
          <el-pagination
            v-model:current-page="currentPage"
            v-model:page-size="pageSize"
            :page-sizes="[10, 20, 50, 100]"
            :total="total"
            layout="total, sizes, prev, pager, next, jumper"
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
          />
        </div>
        </el-main>
      </el-container>
    </el-container>


    <!-- 分享详情对话框 -->
    <el-dialog v-model="showShareDetailDialog" title="分享详情" width="600px">
      <div v-if="currentShare" class="share-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="分享文件">{{ currentShare.fileName }}</el-descriptions-item>
          <el-descriptions-item label="分享链接">
            <div class="share-link">
              <span>{{ currentShare.shareUrl }}</span>
              <el-button size="small" text @click="copyShareLink(currentShare)">
                <el-icon><CopyDocument /></el-icon>
              </el-button>
            </div>
          </el-descriptions-item>
          <el-descriptions-item label="提取码">
            {{ currentShare.password || '无' }}
          </el-descriptions-item>
          <el-descriptions-item label="访问次数">{{ currentShare.visitCount }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag v-if="currentShare.status === 1" type="success">有效</el-tag>
            <el-tag v-else type="danger">已过期</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatTime(currentShare.createTime) }}</el-descriptions-item>
          <el-descriptions-item label="过期时间">
            {{ currentShare.expireTime ? formatTime(currentShare.expireTime) : '永久有效' }}
          </el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>

    <!-- 编辑分享对话框 -->
    <el-dialog v-model="showEditShareDialog" title="编辑分享" width="500px">
      <el-form :model="editShareForm" :rules="editShareRules" ref="editShareFormRef" label-width="100px">
        <el-form-item label="分享名称" prop="shareName">
          <el-input v-model="editShareForm.shareName" placeholder="请输入分享名称" />
        </el-form-item>
        <el-form-item label="访问权限">
          <el-radio-group v-model="editShareForm.permissions">
            <el-radio :label="1">仅预览</el-radio>
            <el-radio :label="2">可下载</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="提取码">
          <div style="display: flex; align-items: center; gap: 10px;">
            <el-switch v-model="editShareForm.needPassword" />
            <el-input
              v-if="editShareForm.needPassword"
              v-model="editShareForm.password"
              placeholder="4位提取码"
              maxlength="4"
              style="width: 120px"
              prop="password"
            />
            <el-button v-if="editShareForm.needPassword" size="small" @click="generateEditPassword">
              随机生成
            </el-button>
          </div>
        </el-form-item>
        <el-form-item label="有效期">
          <el-radio-group v-model="editShareForm.expireDays">
            <el-radio :label="1">1天</el-radio>
            <el-radio :label="7">7天</el-radio>
            <el-radio :label="30">30天</el-radio>
            <el-radio :label="-1">永久有效</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showEditShareDialog = false">取消</el-button>
        <el-button type="primary" @click="handleSaveEdit">保存</el-button>
      </template>
    </el-dialog>

    <!-- 个人信息对话框 -->
    <UserProfileDialog v-model="showProfileDialog" />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted, watch } from 'vue'
import { ElMessage, ElMessageBox, type FormInstance, type FormRules } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { getMyShareList, cancelShare, updateShare, type ShareInfo, type ShareListResponse } from '@/api/share'
import UserProfileDialog from '@/components/UserProfileDialog.vue'
import {
  View,
  Edit,
  Delete,
  CopyDocument,
  Share,
  Folder,
  Document,
  Search,
  User,
  ArrowDown,
  Upload
} from '@element-plus/icons-vue'

const userStore = useUserStore()

// 本地分享信息扩展（用于显示）
interface ShareDisplayInfo extends ShareInfo {
  fileName?: string
  shareUrl?: string
}

// 响应式数据
const loading = ref(false)
const createLoading = ref(false)
const shareType = ref<'all' | 'active' | 'expired'>('all')
const searchKeyword = ref('')
const shareList = ref<ShareDisplayInfo[]>([])
const selectedShares = ref<ShareDisplayInfo[]>([])
const currentPage = ref(1)
const pageSize = ref(20)
const total = ref(0)

// 对话框状态
const showShareDetailDialog = ref(false)
const showEditShareDialog = ref(false)
const showCreateShareDialog = ref(false)
const showFileSelectDialog = ref(false)
const showProfileDialog = ref(false)
const currentShare = ref<ShareDisplayInfo | null>(null)

// 编辑分享表单
const editShareFormRef = ref<FormInstance>()
const editShareForm = reactive({
  shareName: '',
  permissions: 2,
  needPassword: false,
  password: '',
  expireDays: 7
})

const editShareRules: FormRules = {
  shareName: [
    { required: true, message: '请输入分享名称', trigger: 'blur' },
    { min: 1, max: 50, message: '分享名称长度为1-50个字符', trigger: 'blur' }
  ],
  password: [
    {
      validator: (rule: any, value: string, callback: Function) => {
        if (editShareForm.needPassword && (!value || value.length !== 4)) {
          callback(new Error('请输入4位提取码'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 工具方法
const formatFileSize = (size: number): string => {
  if (size < 1024) return size + ' B'
  if (size < 1024 * 1024) return (size / 1024).toFixed(2) + ' KB'
  if (size < 1024 * 1024 * 1024) return (size / (1024 * 1024)).toFixed(2) + ' MB'
  return (size / (1024 * 1024 * 1024)).toFixed(2) + ' GB'
}

const formatDateTime = (dateTime: string): string => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

const formatTime = (dateTime: string): string => {
  return new Date(dateTime).toLocaleString('zh-CN')
}

// 处理用户菜单命令
const handleCommand = (command: string) => {
  switch (command) {
    case 'profile':
      showProfileDialog.value = true
      break
    case 'logout':
      userStore.logout()
      break
  }
}

// 获取分享列表
const fetchShareList = async () => {
  try {
    loading.value = true

    const response = await getMyShareList({
      page: currentPage.value,
      size: pageSize.value,
      orderBy: 'createTime',
      orderType: 'desc'
    })

    // 转换数据格式并生成分享链接
    const baseUrl = window.location.origin
    shareList.value = response.content.map(share => ({
      ...share,
      shareUrl: `${baseUrl}/share/${share.shareCode}`
    }))

    total.value = response.total
  } catch (error: any) {
    ElMessage.error(error.message || '获取分享列表失败')
  } finally {
    loading.value = false
  }
}

// 处理选择变化
const handleSelectionChange = (selection: ShareDisplayInfo[]) => {
  selectedShares.value = selection
}

// 查看分享详情
const handleViewShare = (share: ShareDisplayInfo) => {
  currentShare.value = share
  showShareDetailDialog.value = true
}

// 编辑分享
const handleEditShare = (share: ShareDisplayInfo) => {
  currentShare.value = share
  editShareForm.shareName = share.shareName
  editShareForm.permissions = share.permissions
  editShareForm.needPassword = !!share.password
  editShareForm.password = share.password || ''

  // 计算当前有效期设置
  if (share.expireTime) {
    const expireDate = new Date(share.expireTime)
    const createDate = new Date(share.createTime)
    const diffDays = Math.ceil((expireDate.getTime() - createDate.getTime()) / (1000 * 60 * 60 * 24))
    if ([1, 7, 30].includes(diffDays)) {
      editShareForm.expireDays = diffDays
    } else {
      editShareForm.expireDays = 30
    }
  } else {
    editShareForm.expireDays = -1 // 永久有效
  }

  showEditShareDialog.value = true
}

// 生成随机提取码
const generateEditPassword = () => {
  const chars = 'abcdefghijklmnopqrstuvwxyz0123456789'
  let password = ''
  for (let i = 0; i < 4; i++) {
    password += chars.charAt(Math.floor(Math.random() * chars.length))
  }
  editShareForm.password = password
}

// 保存编辑
const handleSaveEdit = async () => {
  if (!editShareFormRef.value || !currentShare.value) return

  try {
    const valid = await editShareFormRef.value.validate()
    if (!valid) return

    // 计算过期时间
    let expireTimeStr = ''
    if (editShareForm.expireDays > 0) {
      const expireDate = new Date()
      expireDate.setDate(expireDate.getDate() + editShareForm.expireDays)
      expireTimeStr = expireDate.toISOString().slice(0, 19).replace('T', ' ')
    }

    await updateShare(currentShare.value.id, {
      shareName: editShareForm.shareName,
      permissions: editShareForm.permissions,
      password: editShareForm.needPassword ? editShareForm.password : undefined,
      expireTimeStr: expireTimeStr || undefined
    })

    ElMessage.success('分享更新成功')
    showEditShareDialog.value = false
    fetchShareList()
  } catch (error: any) {
    ElMessage.error(error.message || '更新分享失败')
  }
}

// 取消分享
const handleCancelShare = async (share: ShareDisplayInfo) => {
  try {
    await ElMessageBox.confirm(
      `确定要取消分享 "${share.shareName}" 吗？`,
      '确认取消',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    await cancelShare(share.id)
    ElMessage.success('分享已取消')
    fetchShareList()
  } catch (error: any) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '取消分享失败')
    }
  }
}

// 复制分享链接
const copyShareLink = async (share: ShareDisplayInfo) => {
  try {
    let copyText = `分享链接: ${share.shareUrl}`
    if (share.password) {
      copyText += `\n提取码: ${share.password}`
    }
    await navigator.clipboard.writeText(copyText)
    ElMessage.success('已复制到剪贴板')
  } catch {
    ElMessage.error('复制失败')
  }
}

// 创建分享（占位方法，实际功能在FilesView中）
const handleCreateShare = () => {
  ElMessage.info('请到文件页面创建分享')
  // 跳转到文件页面
  // router.push('/files')
}

// 处理搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchShareList()
}

// 处理当前页变化
const handleCurrentChange = (page: number) => {
  currentPage.value = page
  fetchShareList()
}

// 处理页面大小变化
const handleSizeChange = (size: number) => {
  pageSize.value = size
  currentPage.value = 1
  fetchShareList()
}

// 重置分享表单（占位方法）
const resetShareForm = () => {
  // 这个方法是为了兼容模板中的调用，实际不需要做任何事情
  // 因为我们已经移除了创建分享的对话框
}

// 监听分享类型变化
watch(shareType, () => {
  currentPage.value = 1
  fetchShareList()
})


// 初始化
onMounted(() => {
  fetchShareList()
})
</script>

<style scoped>
.share-container {
  height: 100vh;
  width: 100vw;
  background: #f8f9fa;
}

.el-container {
  height: 100%;
  width: 100%;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
  padding: 0 20px;
}

.header-left h2 {
  margin: 0;
  color: #409eff;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 5px;
  cursor: pointer;
  padding: 8px 12px;
  border-radius: 4px;
  transition: background-color 0.3s;
}

.user-info:hover {
  background-color: #f5f5f5;
}

.sidebar {
  background-color: #f5f5f5;
  border-right: 1px solid #e6e6e6;
}

.main-content {
  background: #f8f9fa;
  padding: 0;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.page-title h3 {
  margin: 0;
  color: #333;
}

.header-left h2 {
  margin: 0;
  color: #333;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 15px 20px;
  background: #fff;
  border-bottom: 1px solid #e6e6e6;
}

.main-content {
  padding: 0;
}

.share-content {
  padding: 20px;
  min-height: 400px;
}

.file-name-cell {
  display: flex;
  align-items: center;
  gap: 8px;
}

.file-icon {
  color: #409eff;
}

.file-name {
  cursor: pointer;
}

.file-name:hover {
  color: #409eff;
}

.share-link {
  display: flex;
  align-items: center;
  gap: 8px;
}

.link-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.no-password {
  color: #999;
}

.pagination {
  display: flex;
  justify-content: center;
  padding: 20px;
  background: #fff;
}

.selected-files {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.file-selector {
  max-height: 400px;
  overflow-y: auto;
}

.share-detail .share-link {
  max-width: 300px;
}
</style>